package com.dotflat.cookbook.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.dotflat.cookbook.service.TongBangAPIResult;
import com.dotflat.cookbook.service.TongBangCookbookService;
import com.dotflat.cookbook.service.TongBangTokenResult;
import com.google.common.collect.ImmutableMap;
import com.matt.commons.dto.sso.AreaDTO;
import com.matt.commons.exception.BusinessException;
import com.matt.commons.utils.DateUtil;
import com.matt.commons.utils.HttpClientUtil;
import com.matt.foundation.model.ErrorCode;
import com.matt.service.remoteCall.DTO.DictDataDTO;
import com.matt.service.remoteCall.SsoCallService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

@Service
public class TongBangCookbookServiceImpl implements TongBangCookbookService {

    @Autowired
    private SsoCallService ssoCallService;

    private final static String TONGBANG_TOKEN_API = "http://sdk.tb-n.com:1117/api/post";
    private final static String TONGBANG_CREARE_AREA_API = "http://tbpt.tb-n.com/tbyypt/createyey";
    private final static String TB_COOKBOOK_CONFIG_TYPE_KEY = "CookbookConfig";
    
    private String createToken_appid = "tb4743983520Lekang";

    private String createToken_appsecret = "788c5eb61e6c4e1bab56c69fa40647bd";

    private String datasource_utype = "Lekang";

//    @Value("${teach.cookbook.tongbang.datasource.appid}")
//    private String datasource_appid;
//
//    @Value("${teach.cookbook.tongbang.datasource.appsecret}")
//    private String datasource_appsecret;

    private String tongBangToken(AreaDTO area) {

        Map headers = new HashMap();
        Map params = ImmutableMap.of("t", "credential", "appid",createToken_appid, "appsecret",createToken_appsecret);

        String tokenJson = null;
        try {
            tokenJson = HttpClientUtil.sendPost(TONGBANG_TOKEN_API, params, headers);
        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.MAP_CONVERT_ERROR, "获取食谱服务token失败");
        }
        if (StringUtils.isEmpty(tokenJson)) {
            throw new BusinessException(ErrorCode.MAP_CONVERT_ERROR, "获取食谱服务token失败");
        }
        TongBangTokenResult token = JSONObject.parseObject(tokenJson, TongBangTokenResult.class);

        if (token == null){
            throw new BusinessException(ErrorCode.MAP_CONVERT_ERROR, "获取食谱服务token失败！");
        }

        if (StringUtils.isBlank(token.getToken())){
            throw new BusinessException(ErrorCode.ERROR, "食谱服务：" + token.mess);
        }

        return token.getToken();
    }

    public boolean isTongBangAreaSynced(String ticket, String areaId){

        DictDataDTO dict = new DictDataDTO("0", areaId,null, TB_COOKBOOK_CONFIG_TYPE_KEY);

        //TODO: 先检查是否已经有创建好的童帮信息
        //TODO: 若已经存在就不需要重复创建
        //为真时代表不存在
        List<DictDataDTO> result = ssoCallService.getDictData(ticket,dict);
        return (result != null && result.size() > 0);
    }

    public void tongbangAreaCreate(String ticket, AreaDTO area) {
        //收到了token，创建远端幼儿园
        //TODO: 先检查是否已经有创建好的童帮信息
        //TODO: 若已经存在就不需要重复创建
        //为真时代表不存在
        boolean v = isTongBangAreaSynced(ticket, area.getId());
        if (!v){
            String token = tongBangToken(area);
            Map headers = new HashMap();
            Map params = new HashMap();
            params.put("utype", datasource_utype);
            params.put("token", token);
            params.put("school_id", area.getId());
            params.put("school_name", handleSpecChar(area.getName()));
            params.put("address", handleSpecChar(area.getName()));
            params.put("area", "370523");
            params.put("leader_name", handleSpecChar(area.getName()));
            params.put("leader_phone", getRandomTel());
            params.put("created_at", DateUtil.toNormalString(new Date()));
            params.put("updated_at", DateUtil.toNormalString(new Date()));

            String responseJson = null;
            try {
                responseJson = HttpClientUtil.sendPost(TONGBANG_CREARE_AREA_API, params, headers);
            } catch (IOException e) {
                e.printStackTrace();
                throw new BusinessException(ErrorCode.MAP_CONVERT_ERROR, "获取食谱服务token失败");
            }
            if (StringUtils.isEmpty(responseJson)) {
                throw new BusinessException(ErrorCode.MAP_CONVERT_ERROR, "获取食谱服务token失败!");
            }

            TongBangAPIResult result = JSONObject.parseObject(responseJson, TongBangAPIResult.class);
            if (!"0".equals(result.getReturn_code())) {
                throw new BusinessException(ErrorCode.TEST_MORE_THAN_LIMIT, "食谱服务创建园区失败");
            }

            //保存配置
            //增加
//        YikangDataMap ydm = new YikangDataMap();
//        ydm.DataType = "TongBang";
//        ydm.LekangId = orgId;
//        ydm.YikangId = Convert.ToInt32(model.yey_id);
//        ydm.YikangValue = kg.KgName;
//        new YikangDataMapLogic().Add(ydm);

            //Boolean addAreaSetting(String key, String value, String description, String extension, String areaId, String type);
            ssoCallService.addAreaSetting("DataType", "TongBang", "菜谱配置类型", "", area.getId(), TB_COOKBOOK_CONFIG_TYPE_KEY);
            ssoCallService.addAreaSetting("Data", result.getData(), "菜谱配置Data", "", area.getId(), TB_COOKBOOK_CONFIG_TYPE_KEY);
            ssoCallService.addAreaSetting("Id", result.getYey_id(), "远端id", "", area.getId(), TB_COOKBOOK_CONFIG_TYPE_KEY);
            ssoCallService.addAreaSetting("Value", area.getName(), "幼儿园名称", "", area.getId(), TB_COOKBOOK_CONFIG_TYPE_KEY);

        }else{
            throw new BusinessException(ErrorCode.VERSION_ERROR, "不能重复没配置带量食谱");
        } 
    }


    /// <summary>
    /// 处理空格、回车换行字符
    /// 原因：Address中含有\n字符
    /// </summary>
    /// <param name="p"></param>
    /// <returns></returns>
    private String handleSpecChar(String str)
    {
        if (str == null)
        {
            return "";
        }
        else
        {
            str = str.trim().replace("\r", "").replace("\n", "").replace("\r\n", "").replace(" ", "");
            return str;
        }
    }

    /// <summary>
    /// 随机生成手机号
    /// </summary>
    /// <returns></returns>
    private String getRandomTel()
    {
        String[] telStarts = "134,135,136,137,138,139,150,151,152,157,158,159,130,131,132,155,156,133,153,180,181,182,183,185,186,176,187,188,189,177,178".split(",");

        Random ran = new Random(System.currentTimeMillis());

        int index = ran.nextInt(telStarts.length);
        String first = telStarts[index];
        String second = ((ran.nextInt(888) + 10000)+"").substring(1);
        String thrid = ((ran.nextInt(9100) + 10000)+"").substring(1);
        return first + second + thrid;
    }


    public String cookBookURL(String ticket, AreaDTO area)
    {
        DictDataDTO dataParam = new DictDataDTO("0", area.getId(), null,TB_COOKBOOK_CONFIG_TYPE_KEY);
        List<DictDataDTO> dicts = ssoCallService.getDictData(ticket, dataParam);

        TongBangAPIResult result = new TongBangAPIResult();
        for (DictDataDTO dict : dicts){
            if ("Id".equals(dict.getDictLabel())){
                result.setYey_id(dict.getDictValue());
            }else if("Data".equals(dict.getDictLabel())){
                result.setData(dict.getDictValue());
            }else if("Value".equals(dict.getDictLabel())){
                result.setAreaName(dict.getDictValue());
            }
        }

        if (StringUtils.isNoneBlank(result.getYey_id(), result.getData())) //示范、长治市泽馨苑幼儿园  orgId == 47 || orgId == 3400
        {
            String token = tongBangToken(area);

            String utype = datasource_utype;
            String yey_id = result.getYey_id();
            String yey_name = result.getAreaName();
            String url = String.format("http://tb-n.com/tongbang/authlogin?utype=%s&token=%s&yey_id=%s&yey_name=%s&menu_type=peican",
                    utype, token, yey_id, yey_name);
            return url;
        }else{
            throw new BusinessException(ErrorCode.VERSION_ERROR, "当前园区还没配置带量食谱");
        }
    }

}
